//
// Created by tang on 23-4-23.
//

#include "utils.hpp"

std::string to_string (CXString str)
{
    std::string ret;
    ret = clang_getCString (str);
    clang_disposeString (str);
    return ret;
}

std::vector<std::string> split (std::string input, std::string pat)
{
    std::vector<std::string> ret_list;
    while (true)
    {
        size_t      index    = input.find(pat);
        std::string sub_list = input.substr(0, index);
        if (!sub_list.empty())
        {

            ret_list.push_back(sub_list);
        }
        input.erase(0, index + pat.size());
        if (index == std::string::npos)
        {
            break;
        }
    }
    return ret_list;
}

std::string trim(const std::string& context)
{

    std::string ret_string = context;

    ret_string = ret_string.erase(0, ret_string.find_first_not_of(" "));
    ret_string = ret_string.erase(ret_string.find_last_not_of(" ") + 1);

    return ret_string;
}

std::string trim(std::string& source_string, const std::string& trim_chars)
{
    size_t left_pos = source_string.find_first_not_of(trim_chars);
    if (left_pos == std::string::npos)
    {
        source_string = std::string();
    }
    else
    {
        size_t right_pos = source_string.find_last_not_of(trim_chars);
        source_string    = source_string.substr(left_pos, right_pos - left_pos + 1);
    }
    return source_string;
}

std::string getTypeNameWithoutNamespace(const CursorType& type)
{
    std::string&& type_name = type.display_name();
    return type_name;
}

std::string getNameWithoutFirstM(std::string& name)
{
    std::string result = name;
    if (name.size() > 2 && name[0] == 'm' && name[1] == '_')
    {
        result = name.substr(2);
    }
    return result;
}

void replaceAll(std::string& resource_str, std::string sub_str, std::string new_str)
{
    std::string::size_type pos = 0;
    while ((pos = resource_str.find(sub_str)) != std::string::npos)
    {
        resource_str = resource_str.replace(pos, sub_str.length(), new_str);
    }
    return;
}

std::string getStringWithoutQuot(std::string input)
{
    size_t left  = input.find_first_of('\"') + 1;
    size_t right = input.find_last_of('\"');
    if (left > 0 && right < input.size() && left < right)
    {
        return input.substr(left, right - left);
    }
    else
    {
        return input;
    }
}
